#!/usr/bin/env python
# coding=utf-8
# -*- coding: utf-8 -*-
import logging
import traceback
from datetime import datetime
from flask import render_template, url_for, redirect, request, flash, session, Blueprint, current_app
from flask_login import current_user
from flask_mail import Message
from models.model import User
from common.utils import admin_pwd_digest
from config import MyConfObj
from models.base import db

user = Blueprint('user', __name__, url_prefix="/user")

log = logging.getLogger(__file__)


@user.errorhandler(404)
def page_not_found():
    return render_template('404.html'), 404


@user.route('/error/404')
def error_404():
    return render_template('404.html'), 404


@user.route('/error')
def error(content='404'):
    return render_template('/error.html', content=content)


@user.route('/login/', methods=['GET', 'POST'])
def login():
    """
    登录一
    :return:
    """
    try:
        if request.method == "GET":
            next = request.args.get("next")
            if not next:
                next = url_for("user.login")
            return render_template("login.html", user=None, next=next)
        else:
            next = request.form.get("next")
            if not next:
                next = url_for('article.article_list')
            name = request.form.get("username")
            password = request.form.get("password")
            if not name:
                message = "账号不能为空！"
                return render_template("login.html", message=message)
            if not password:
                message1 = "密码不能为空！"
                return render_template("login.html", message1=message1)
            login_user = User.query.get_user_by_name(name=name)
            if not login_user:
                message = '账号不存在'
                return render_template("login.html", message=message)
            else:
                if login_user.password != admin_pwd_digest(password):
                    message1 = "密码错误"
                    return render_template("login.html", message1=message1)
                else:
                    session[MyConfObj.BACKEND_UNAME] = login_user.name
                    session[MyConfObj.BACKEND_UID] = login_user.id
                    return redirect(next)
    except:
        log.info("login -----%s" % traceback.format_exc())
        return render_template("login.html")


@user.route('/logout')
def logout():
    session.pop('logged_in', None)
    session.clear()
    flash('You were logged out')
    return redirect(url_for('index'))


@user.route('/register', methods=['GET', 'POST'])
def register():
    #注册
    if request.method == 'POST':
        email = request.form.get("email")
        username = request.form.get("username")
        password = request.form.get("password")
        user = User(email=email,
                    username=username,
                    password=password)
        db.session.add(user)
        db.session.commit()  #这里不能等数据库自动保存，因为用户在验证时需要登录
        token = user.generate_confirmation_token()  #生成HASH码
        send_email(user.email, 'Confirm Your Account',
                    'auth/email/confirm', user=user, token=token)#发送验证信息
        flash('邮件已经发送！')
        return redirect(url_for('auth.login'))#重定向到登录页面
    return render_template('auth/register.html')


def send_email(to, subject, template, **kwargs):
    app = current_app._get_current_object()
    msg = Message(subject, sender='418836702@qq.com', recipients=[to])
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
    with app.app_context():
        mail.send(msg) #发射


@user.route('/unconfirmed')
def unconfirmed():
    if current_user.is_anonymous or current_user.confirmed:
        return redirect(url_for('main.index'))
    return render_template('auth/unconfirmed.html')


@user.route('/confirm/<token>')
# @login_required
def confirm(token):
    if current_user.confirmed:
        #如果你已经激活过了
        return redirect(url_for('main.index'))
    if current_user.confirm(token):
        #去激活并且激活成功了
        flash('O了！')
    else:
        flash('你是盗号的还是迟到鬼?')
    return redirect(url_for('main.index'))


def create_pwd(pwd):
    return admin_pwd_digest(pwd)


if __name__ == '__main__':
    print create_pwd('123456')
